﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ActionWall {
	// === Public =====================================================================================================
	public static void CreateOrChangeObjectUsingWall() {
		var transObjModel = MapEditorBaseData.GetInstance.TransparentObject.ElementModel;
		var transObjPos = new Vector2(transObjModel.Position.x, transObjModel.Position.z);
		var foundObjs = new List<ElementCtrl>();
		foreach (var editorElement in Game.GetGameModel().Elements) {
			if (transObjPos.x.Equals(editorElement.ElementModel.Position.x) &&
				transObjPos.y.Equals(editorElement.ElementModel.Position.z)) {
				foundObjs.Add(editorElement);
			}
		}
		switch (foundObjs.Count) {
			case 0:		// Create tail and wall
				CreateTail(transObjPos);
				CreateWall(transObjPos, transObjModel.TexturePath);
				return;
			case 1:		// Tail found, create wall
				CreateWall(transObjPos, transObjModel.TexturePath);
				return;
			default:	// Wall found, change the texture
				foreach (var element in foundObjs.Where(element => ElementType.Wall.Equals(element.ElementModel.ElementType))) {
					element.SetTexture(transObjModel.TexturePath);
					return;
				}
				return;
		}
	}

	// === Private ====================================================================================================
	private static void CreateWall(Vector2 transObjPos, string transObjTexturePath) {
		var properties = new PropertyElementWall(transObjPos, transObjTexturePath);
		var element = Creators.Element.Create(properties);
		Game.GetGameModel().AddElement(element);
	}

	private static void CreateTail(Vector2 transObjPos) {
		var properties = new PropertyElementTile(transObjPos, Managers.Texture.GetFirstTexture(ElementType.Tile));
		var element = Creators.Element.Create(properties);
		Game.GetGameModel().AddElement(element);
	}
}